import uuid
import random

from django.core.paginator import Paginator
from django.db.models import Q

from rest_framework.decorators import api_view
from rest_framework.response import Response

from stock.models import Warehouse, Goods, Stock
from stock.serializer import WarehouseSerializer, GoodsSerializer, StockSerializer, StockDetailSerializer
from user.models import Staff
from utils.decorator_ import PermissionCheck


@PermissionCheck('stock.view_warehouse')
@api_view(['get'])
def warehouse(request):
    """
        查询仓库
    :param request:
    :return:
    """
    # 查询参数： page 页号, size 每页显示的条目数量
    page = int(request.GET.get('page', '1'))
    size = int(request.GET.get('size', '20'))
    staff = Staff.objects.get(pk=request.user.pk)
    if staff.role.role_id in ['4a1286cefec64c74a39b7fa18a0a6848', '4c2a53b3843e49ebadc4eb56b6f7e86b']:
        data = Warehouse.objects.all()
    else:
        data = Warehouse.objects.filter(staff_name=staff.name)
    paginator = Paginator(data, size)
    pager = paginator.page(page)
    # 模型实例化
    approve = WarehouseSerializer(pager.object_list, many=True)
    return Response({
        'data': approve.data,
        'total': paginator.count,
        'page': pager.number,  # page当前页号
        'pageSize': size,
        'pages': paginator.num_pages  # 总页数
    })

@PermissionCheck('stock.view_stcok')
@api_view(['get'])
def all_stock(request):
    """
        查看具体商品的库存
    :param request:
    :return:
    """
    # 查询参数： page 页号, size 每页显示的条目数量
    page = int(request.GET.get('page', '1'))
    size = int(request.GET.get('size', '20'))
    staff = Staff.objects.get(pk=request.user.pk)
    if staff.role.role_id in ['4a1286cefec64c74a39b7fa18a0a6848', '4c2a53b3843e49ebadc4eb56b6f7e86b']:
        data = Stock.objects.all()
    else:
        data = Stock.objects.filter(num=staff.num)
    paginator = Paginator(data, size)
    pager = paginator.page(page)
    # 模型实例化
    approve = StockSerializer(pager.object_list, many=True)
    return Response({
        'data': approve.data,
        'total': paginator.count,
        'page': pager.number,  # page当前页号
        'pageSize': size,
        'pages': paginator.num_pages  # 总页数
    })

@PermissionCheck('stock.view_goods')
@api_view(['get'])
def goods(request):
    """
        查看所有商品接口
    :param request:
    :return:
    """
    if request.user:
        goods = Goods.objects.all()
        ret = GoodsSerializer(goods, many=True)
        return Response(ret.data)

@PermissionCheck('stock.view_stcok')
@api_view(['get'])
def stock(request,pk):
    """
        查看库存详情
    :param request:
    :return:
    """
    if request.user:
        stock1 = Stock.objects.get(pk=pk)
        ret = StockDetailSerializer(stock1, many=False)
        return Response(ret.data)

@PermissionCheck('stock.view_stcok')
@api_view(['get'])
def check_stock(request):
    """
        模糊查询，通过关键字查询 stock_id   city 等信息
    :param request:
    :return:
    """
    para = request.GET.get('para')
    stock = Stock.objects.filter(Q(city__contains=para) | Q(num__contains=para))
    ret = StockSerializer(stock, many=True)
    return Response(ret.data)

@PermissionCheck('stock.change_stcok')
@api_view(['post'])
def change_stock(request):
    """
        进出库，仓库数量调整
    :param request:
    :return:
    """
    type = request.data.get('type')
    stock_id = request.data.get('stock_id')
    number = int(request.data.get('num'))
    stock = Stock.objects.get(stock_id=stock_id)
    if type == '出库':
        if stock.count < abs(number):
            return Response({'msg': '亲，仓库数量不足，请从从其他地方调货', '当前剩余 count': '{}'.format(stock.count)})
        else:
            stock.count -= number
            stock.save()
        return Response({'msg': '提货成功，请出库'})
    elif type == '入库':
        stock.count += number
        stock.save()
        return Response({'msg':'入库成功'})
    else:
        return Response({'msg':'不支持此操作'})

@PermissionCheck('stock.add_warehouse')
@api_view(['post'])
def add_ware(request):
    """
        添加仓库
    :param request:
    :return:
    """
    ware_id = uuid.uuid4().hex
    name = request.data.get('name')
    data = {key:request.data.get(key) for key in request.data}
    address = data['address']
    warehouse = Warehouse.objects.filter(address=address)
    if warehouse:
        return Response({'msg': '该仓库已存在'})
    else:
        Warehouse.objects.create(ware_id=ware_id, **data)
        return Response({'msg': '仓库创建成功'})

@PermissionCheck('stock.add_goods')
@api_view(['post'])
def add_goods(request):
    """
        添加商品，之前仓库未进此类型商品
    :param request:
    :return:
    """
    goods_id = uuid.uuid4().hex
    num = '69'+''.join([str(random.randint(0,9)) for i in range(8)])
    data = {key:request.data.get(key) for key in request.data}
    name = data['name']
    qs = Goods.objects.filter(Q(name=name)|Q(num=num))
    if qs:
        return Response({'msg':'商品已存在'})
    else:
        Goods.objects.create(goods_id=goods_id,num=num,**data)
    return Response({'msg': '商品添加成功'})

@PermissionCheck('stock.add_stcok')
@api_view(['post'])
def add_stock(request):
    """
        添加新商品库存
    :param request:
    :return:
    """
    data = { key:request.data.get(key) for key in request.data }
    stock_id = uuid.uuid4().hex
    stock = Stock.objects.filter(Q(goods_id=data['goods_id']))
    if stock:
        return Response({'msg':'该商品已存在，请直接添加库存'})
    else:
        Stock.objects.create(stock_id=stock_id,**data)
    return Response({'msg':'商品添加成功'})